import logging

import requests
from django.conf import settings

logger = logging.getLogger(__name__)


def ping_google(sitemap_url=None):
    """
    Alerts Google that the sitemap for the current site has been updated.
    If sitemap_url is provided, it should be an absolute path to the sitemap
    for this site -- e.g., '/sitemap.xml'. If sitemap_url is not provided, this
    function will attempt to deduce it by using urls.reverse().
    """
    import urllib
    from django.contrib.sites.models import Site
    from django.core.exceptions import ImproperlyConfigured
    
    if sitemap_url is None:
        try:
            # First, try to get the "django.contrib.sitemaps" app's URL pattern.
            from django.urls import reverse
            sitemap_url = reverse('django.contrib.sitemaps.views.sitemap')
        except ImportError:
            raise ImproperlyConfigured("ping_google requires either sitemap_url argument or django.contrib.sitemaps in your INSTALLED_APPS.")
        except:
            raise ImproperlyConfigured("ping_google requires either a sitemap_url argument or django.contrib.sitemaps to be installed in your INSTALLED_APPS.")

    current_site = Site.objects.get_current()
    url = "http://www.google.com/webmasters/tools/ping"
    params = urllib.parse.urlencode({'sitemap': f'http://{current_site.domain}{sitemap_url}'})
    
    try:
        urllib.request.urlopen(f"{url}?{params}")
    except Exception:
        # Google ping errors are not critical, so we ignore them
        pass


class SpiderNotify():
    @staticmethod
    def baidu_notify(urls):
        try:
            data = '\n'.join(urls)
            result = requests.post(settings.BAIDU_NOTIFY_URL, data=data)
            logger.info(result.text)
        except Exception as e:
            logger.error(e)

    @staticmethod
    def __google_notify():
        try:
            ping_google('/sitemap.xml')
        except Exception as e:
            logger.error(e)

    @staticmethod
    def notify(url):

        SpiderNotify.baidu_notify(url)
        SpiderNotify.__google_notify()
